from typing import Set
from redis import Redis
import redis
from app.common import get_redis
#from app.dependencies.redis import get_redis

from fastapi import APIRouter, Depends, Request, Query

router = APIRouter()


@router.get("/smembers", summary="集合成员")
async def smembers(request: Request, name: str=Query('testset', title="集合名"), 
                   r: Redis=Depends(get_redis)):
    #request.app.state.redis.smembers(name)
    set: Set = r.smembers(name)
    #print(v, type(v))
    return {"members": set}

@router.get("/sismember", summary="查询成员是否存在")
async def sismember(request: Request, name: str=Query('testset', title="集合名"),
                   member: str=Query('foo', title="成员"), 
                   r: Redis=Depends(get_redis)):
    #request.app.state.redis.smembers(name)
    res= r.sismember(name, member)
    #print(v, type(v))
    return {"result": res}

@router.get("/scard", summary="统计成员数")
async def scard(request: Request, sname: str=Query('testset', title="集合名"), 
                   r: Redis=Depends(get_redis)):
    #request.app.state.redis.smembers(name)
    res = r.scard(sname)
    #print(v, type(v))
    return {'total': res}

@router.get("/sadd", summary="添加集合成员")
async def sadd(request: Request, name: str=Query('testset', title="集合名"), 
                   members: tuple=Query(('foo'), title="成员(多个成员用空格隔开)"), 
                   r: Redis=Depends(get_redis)):
    #request.app.state.redis.smembers(name)
    res = r.sadd(name, *members)
    #print(v, type(v))
    return {'added': res}

@router.get("/srem", summary="移除集合成员")
async def srem(request: Request, name: str=Query('testset', title="集合名"), 
                   members: tuple=Query(('foo'), title="成员(多个成员用空格隔开)"), 
                   r: Redis=Depends(get_redis)):
    #request.app.state.redis.smembers(name)
    res = r.srem(name, *members)
    #print(v, type(v))
    return {'removed': res}

@router.get("/rset", summary="设置键值")
async def rset(request: Request, rkey: str=Query('test:msg', title="参数key"),
                rvalue: str | int=Query('foo...', title="参数value"),
                r: Redis=Depends(get_redis)):
    # 等待redis写入  await异步变同步 如果不关心结果可以不用await，但是这里下一步要取值，必须得先等存完值 后再取值
    #request.app.state.redis.set(rkey, rvalue)
    r.set(rkey, rvalue)
    # 等待 redis读取
    v = r.get(rkey)
    #v = request.app.state.redis.get(rkey)
    print(v, type(v))
    return {"key": rkey, "value": v}

@router.get("/rget", summary="获取键值")
async def rget(request: Request, rkey: str=Query('test:msg', title="参数Key"), 
                   r: Redis=Depends(get_redis)):
    # 等待 redis读取
    #v = request.app.state.redis.get(rkey)
    v = r.get(rkey)
    print(v, type(v))
    return {"value": v}

